package com.sk.bilibili.service;

import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.dto.DanmuInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author 邵康
 * @date 2021/12/2 14:15
 */
@Service
public class VideoSocketService extends BaseBroadcastSocketService<DanmuInfo>{

    @Autowired
    private DanmuService danmuService;

    @Override
    protected void afterAddNew(Integer videoId, Session session) {
        broadcastOnlineChange(videoId);
    }

    private void broadcastOnlineChange(Integer videoId) {
        Set<Session> sessions = sessionMap.get(videoId);
        broadcastMessage(videoId,DanmuInfo.onlineInfo(sessions.size()));
    }

    @Override
    protected void afterRemove(Integer videoId, Session session) {
        broadcastOnlineChange(videoId);
    }

    public void broadcastDanmu(Integer videoId, Danmu danmu) {
        broadcastMessage(videoId,DanmuInfo.danmuInfo(danmu));
        danmu.setVideoId(videoId);
        danmuService.add(danmu);
    }

}